package com.ysm.smfu.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.ysm.smfu.R;
import com.ysm.smfu.area.CityPicker;
import com.ysm.smfu.bean.Friend;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.manager.GlideCircleTransform;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.protocal.MyStringCallBack;
import com.ysm.smfu.timepicker.TimePicker;
import com.ysm.smfu.utils.CircleUtil;
import com.ysm.smfu.utils.FileUtils;
import com.ysm.smfu.utils.JsonUtil;
import com.ysm.smfu.utils.PopupWindowUtil;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.ToastUtils;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.view.AutoRadioGroup;
import com.ysm.smfu.welcome.SharedConfig;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import chatuidemo.db.DBManager;

/**
 * Created by Administrator on 2016/9/26.
 */
public class MyZiLiaoFragment extends MyBaseFragment implements View.OnClickListener {

    @BindView(R.id.ziliao)
    AutoRelativeLayout ziliao;
    @BindView(R.id.fragment_ziliao_img)
    ImageView fragmentZiliaoImg;
    @BindView(R.id.fragment_ziliao_nicheng)
    TextView fragmentZiliaoNicheng;
    @BindView(R.id.fragment_ziliao_nicheng_module)
    AutoLinearLayout fragmentZiliaoNichengModule;
    @BindView(R.id.fragment_ziliao_sex)
    TextView fragmentZiliaoSex;
    @BindView(R.id.fragment_ziliao_sex_module)
    AutoLinearLayout fragmentZiliaoSexModule;
    @BindView(R.id.fragment_ziliao_birthday)
    TextView fragmentZiliaoBirthday;
    @BindView(R.id.fragment_ziliao_birthday_module)
    AutoLinearLayout fragmentZiliaoBirthdayModule;
    @BindView(R.id.fragment_ziliao_diqu)
    TextView fragmentZiliaoDiqu;
    @BindView(R.id.fragment_ziliao_diqu_module)
    AutoLinearLayout fragmentZiliaoDiquModule;

    @BindView(R.id.fragment_nc)
    TextView textView_nc;
    @BindView(R.id.fragment_sex)
    TextView fragment_sex;
    @BindView(R.id.fragment_sr)
    TextView fragment_sr;
    @BindView(R.id.fragment_area)
    TextView fragment_area;

    //    @BindView(R.id.shade)
//    View shade;
    private View pw;
    private EditText editText;
    private TextView alert;
    private AutoRadioGroup sex;
    private TimePicker timePicker;
    private CityPicker fragmentCityPicker;
    private AlertDialog dialog_sex;
    private AlertDialog dialog_nc;
    private String id;
    private String nc;
    private String sr;
    private String dq;
    private String sex1;
    private SharedPreferences currShared;
    private String name;
    private ProgressDialog dialog;
    private String hxId;
    private String is_business;
    private String lastloginTime;
    private String sexIndex = "1";
    private Friend friend;
    private Bitmap bitmap;
    private Bitmap prebitmap;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = UIUtils.inflate(R.layout.fragment_ziliao);
        ButterKnife.bind(this, view);
        SharedPreferences sp = new SharedConfig(UIUtils.getContext()).getCommoneSp();
        name = sp.getString(SpKey.NAME, "");
        currShared = new SharedConfig(UIUtils.getContext(), name).getPrivateSp();
        id = currShared.getString(SpKey.USERID, "");
        nc = currShared.getString(SpKey.NC, "");
        sr = currShared.getString(SpKey.SR, "");
        sex1 = currShared.getString(SpKey.SEX, "");
        dq = currShared.getString(SpKey.DQ, "");
        hxId = currShared.getString(SpKey.HXID, "");
        is_business = currShared.getString(SpKey.IS_BUSINESS, "");
        lastloginTime = currShared.getString(SpKey.LAST_TIME, "");
        String imgAddress = currShared.getString(SpKey.IMAGEADDRESS, "");

        //获取本地头像，默认显示
        //从本地获取图片 ，获取不到则从网络获取
//        prebitmap = MyImageBitmapUtil.getBitmapLoc(name);

        textView_nc.setText(nc);
        fragment_sr.setText(sr);
        fragment_sex.setText(sex1);
        fragment_area.setText(dq);
        if (prebitmap != null)
            fragmentZiliaoImg.setImageBitmap(CircleUtil.toRoundBitmap(getContext(), prebitmap));
        else if (!TextUtils.isEmpty(imgAddress) && !imgAddress.startsWith("null?"))
            Glide.with(MyZiLiaoFragment.this).load(imgAddress).placeholder(R.drawable.myimg2).error(R.drawable.myimg2)
                    .transform(new GlideCircleTransform(UIUtils.getContext()))
                    .into(fragmentZiliaoImg);
        return view;
    }

    boolean isFirst1 = true;
    boolean isFirst2 = true;
    boolean isFirst3 = true;

    @OnClick({R.id.fragment_ziliao_img, R.id.fragment_ziliao_nicheng, R.id.fragment_ziliao_nicheng_module,
            R.id.fragment_ziliao_sex, R.id.fragment_ziliao_sex_module, R.id.fragment_ziliao_birthday,
            R.id.fragment_ziliao_birthday_module, R.id.fragment_ziliao_diqu, R.id.fragment_ziliao_diqu_module,
            R.id.xiugai_comp})
    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.fragment_ziliao_img:
//                选择头像
                pw = PopupWindowUtil.toogleInButton(getActivity(), SpKey.IMG, ziliao, R.layout.fragment_ziliao_img, null);
                if (isFirst1)
                    setPopupListener(pw, 0);
                break;

            case R.id.fragment_ziliao_nicheng_module:
//                选择昵称对话框
                showNcDialog();
                break;

            case R.id.fragment_ziliao_sex_module:
//                选择性别
                showSexDialog();
                break;
            case R.id.fragment_ziliao_birthday_module:
//                设置生日
                View view_diqu = PopupWindowUtil.toogleInButton(getActivity(), SpKey.SR, ziliao, R.layout.sr, null);
                if (isFirst2)
                    setPopupListener(view_diqu, 3);
                break;
            case R.id.fragment_ziliao_diqu_module:
                View shanghu = PopupWindowUtil.toogleInButton(getActivity(), SpKey.DQ, ziliao, R.layout.fragment_area, null);
                if (isFirst3)
                    setPopupListener(shanghu, 4);
                break;
            case R.id.xiugai_comp:
                showDialog();
                updateInfo();
                break;
        }
    }

    /**
     * 正在上传
     */
    private void showDialog() {
        dialog = ProgressDialog.show(getActivity(), "上传进度", "正在上传...", true, false);
        if (dialog.isShowing())
            dialog.dismiss();
        dialog.show();
    }

    public void cancelDialog() {
        if (dialog != null && dialog.isShowing())
            dialog.dismiss();
    }

    /**
     * 上传头像
     */
    private void upDateImage() {
        BaseProtocal.builder(true).upDateImage(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
                    releaseSpace();
                    if (dialog != null && dialog.isShowing())
                        dialog.setMessage("用户头像更新成功");
                    cancelDialog();
//                头像上传成功后，更新用户信息
//                因为接口变动和二维码不添加logo原因，不再需要保持头像到本地
//                MyImageBitmapUtil.saveBitmapLoc(bitmap, name);
                    fragmentZiliaoImg.setImageBitmap(bitmap);

//                  发送广播，更新头像
                    sendImageBroadcast(bitmap, false);
                    getActivity().finish();
                } else {
                    ToastUtils.showToast(JsonUtil.getMessage(response));
                }
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.showErrToast();
                cancelDialog();
            }
        }, decFile, id);
    }

    /**
     * 释放内存
     */
    private void releaseSpace() {
        if (tempFile.exists())
            tempFile.delete();
        if (decFile.exists())
            decFile.delete();
    }

    /**
     * 更新个人信息
     * 请求地址 : app/userAlter
     * 参数 :
     * id:用户ID  perName:用户昵称  sex:性别  	address:地区  birthday:生日
     * sign：签名
     * nonce：随机数
     * timestamp：时间戳
     * 签名字段 :
     * Id ;nonce;timestamp外加key 秘钥
     * 返回结果	 :
     * result:0失败，1:成功
     */
    private void updateInfo() {
        BaseProtocal.builder(true).updateInfo(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("更新用户信息", response);
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
                    // 保存到本地
                    saveToLocal();
                    if (dialog != null && dialog.isShowing())
                        dialog.setMessage("用户信息更新成功，正在上传头像...");
                    if (decFile.length() > 0) {
                        upDateImage();
                    } else {
                        sendImageBroadcast(prebitmap, true);
                        cancelDialog();
                        getActivity().finish();
                    }
                } else {
                    ToastUtils.showToast(getResources().getString(R.string.netError));
                }
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.showErrToast();
                cancelDialog();
            }
        }, id, nc, sexIndex, dq, sr);
    }

    /**
     * 没必要 TODO 同时在MyFragment也保存了一份
     */
    private void saveToLocal() {
        currShared.edit().putString(SpKey.NC, nc).commit();
        currShared.edit().putString(SpKey.SEX, sex1).commit();
        currShared.edit().putString(SpKey.SR, sr).commit();
        currShared.edit().putString(SpKey.DQ, dq).commit();
        currShared.edit().putString(SpKey.IS_BUSINESS, is_business).commit();
        Friend friend = new Friend();
        friend.id = MyZiLiaoFragment.this.id;
        friend.petName = nc;
        friend.hxId = MyZiLiaoFragment.this.hxId;
        friend.sex = sex1;
        friend.birthday = sr;
        friend.address = dq;
        friend.phone = name;
        friend.is_business = is_business;
        friend.lastloginTime = lastloginTime;
        DBManager.getInstance().saveContact2(friend);
    }

    /**
     * 展示性别对话框
     */
    private void showSexDialog() {
        View view = UIUtils.inflate(R.layout.fragment_ziliao_sex);
        dialog_sex = new AlertDialog.Builder(getActivity())
                .setTitle("请选择性别")
                .setView(view)
                .create();
        dialog_sex.show();
        sex = (AutoRadioGroup) view.findViewById(R.id.sex);
        Button confrim = (Button) view.findViewById(R.id.fragment_sex_confirm);
        sex.check(R.id.fragment_women);
        confrim.setOnClickListener(this);
    }

    /**
     * 展示昵称对话框
     */
    private void showNcDialog() {
        View view = UIUtils.inflate(R.layout.fragment_ziliao_nc);
        dialog_nc = new AlertDialog.Builder(getActivity())
                .setTitle("设置昵称")
                .setView(view)
                .create();
        dialog_nc.show();

        editText = (EditText) view.findViewById(R.id.fragment_nc);
        Button button = (Button) view.findViewById(R.id.fragment_nc_confirm);
        alert = (TextView) view.findViewById(R.id.fragment_nc_alert);
        UIUtils.showKeyboard(editText);
        button.setOnClickListener(this);
    }

    public void setPopupListener(View view, int i) {
        switch (i) {
            case 0:
                isFirst1 = false;
                TextView camera = (TextView) view.findViewById(R.id.camera);
                TextView phone = (TextView) view.findViewById(R.id.phone);
                TextView cancel = (TextView) view.findViewById(R.id.cancel);
                camera.setOnClickListener(this);
                phone.setOnClickListener(this);
                cancel.setOnClickListener(this);
                break;
            case 3:
                isFirst2 = false;
                timePicker = (TimePicker) view.findViewById(R.id.timepicker);
                Button confirm = (Button) view.findViewById(R.id.confirm);
                confirm.setOnClickListener(this);
                break;
            case 4:
                isFirst3 = false;
                fragmentCityPicker = (CityPicker) view.findViewById(R.id.fragment_cityPicker);
                Button fragment_area_confirm = (Button) view.findViewById(R.id.fragment_area_confirm);
                fragment_area_confirm.setOnClickListener(this);
                break;
        }
    }
//    @AfterPermissionGranted(RC_CAMERA_PERM)
//    public void cameraTask() {
//        if (EasyPermissions.hasPermissions(getActivity(), perms2)) {
//            //打开扫描界面扫描条形码或二维码
//            Intent openCameraIntent = new Intent(getActivity(), CaptureActivity.class);
//            startActivityForResult(openCameraIntent, 0);
//        } else {
//            showErrorDialog("没有获得摄像头权限，无法打开摄像头，请在设置页面添加该权限");
//        }
//    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.camera:
                cameraPhoto();
                break;
            case R.id.phone:
                takePic();
                break;
            case R.id.cancel:
                PopupWindowUtil.cancel(SpKey.IMG, null);
                break;
            case R.id.fragment_nc_confirm:
                nc = editText.getText().toString().trim();
                if (TextUtils.isEmpty(nc)) {
                    alert.setText("昵称不能为空");
                    break;
                } else {
                    alert.setText("");
                }
                dialog_nc.dismiss();
                textView_nc.setText(nc);
                break;
            case R.id.fragment_sex_confirm:
                if (sex.getCheckedRadioButtonId() == R.id.fragment_man) {
                    sex1 = "男";
                    sexIndex = "1";
                    fragment_sex.setText(sex1);
                    currShared.edit().putString(SpKey.SEX, sex1).commit();
                }
                if (sex.getCheckedRadioButtonId() == R.id.fragment_women) {
                    sex1 = "女";
                    sexIndex = "0";
                    fragment_sex.setText(sex1);
                }
                dialog_sex.dismiss();
                break;
            case R.id.confirm:
                sr = timePicker.getYear() + "-" + timePicker.getMonth() + "-" + timePicker.getDay();
                fragment_sr.setText(sr);
                PopupWindowUtil.cancel(SpKey.SR, null);
                break;
            case R.id.fragment_area_confirm:
                String citys = fragmentCityPicker.getCity_string();
                String[] strings = citys.split("#");
                dq = "";
                for (String str : strings) {
                    dq = dq + str;
                }
                fragment_area.setText(dq);
                PopupWindowUtil.cancel(SpKey.DQ, null);
                break;
        }
    }

    //    相机文件的保存路径
    File tempFile = new File(FileUtils.getDir("dmh_pic"), getPhotoFileName());
    //    相机/相册文件裁剪后的保存路径
    File decFile = new File(FileUtils.getDir("dmh_pic"), getPhotoFileName());

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        PopupWindowUtil.cancel(SpKey.IMG, null);
        if (requestCode == 100 && resultCode == getActivity().RESULT_OK) {
            startPhotoZoom(Uri.fromFile(tempFile), Uri.fromFile(decFile), 150);
        } else if (requestCode == 101 && data != null) {
            setPicToView(data);
        } else if (requestCode == 200 && resultCode == getActivity().RESULT_OK && data != null) {
            //从相册选取成功后，需要从Uri中拿出图片的绝对路径，再调用剪切
//            path = CropUtil.getPath(UIUtils.getContext(), data.getData());
//            tempFile = new File(path);
            startPhotoZoom(data.getData(), Uri.fromFile(decFile), 150);
        } else {
//            ToastUtils.showToast("没有得到相册图片");
        }
    }

    /**
     * 调用相机拍照
     */
    private void cameraPhoto() {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        // 指定调用相机拍照后照片的储存路径
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        startActivityForResult(intent, 100);
    }

    /**
     * 调取相册
     */
    private void takePic() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_PICK);
        this.startActivityForResult(intent, 200);
    }

    private void startPhotoZoom(Uri uri, Uri des, int size) {
        if (uri != null) {
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            // crop为true是设置在开启的intent中设置显示的view可以剪裁
            intent.putExtra("crop", "true");
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // outputX,outputY 是剪裁图片的宽高
            intent.putExtra("outputX", size);
            intent.putExtra("outputY", size);
            intent.putExtra("scale", true);
            //将剪切的图片保存到目标Uri中
            intent.putExtra(MediaStore.EXTRA_OUTPUT, des);
            intent.putExtra("return-data", true);
            intent.putExtra("noFaceDetection", true);
            startActivityForResult(intent, 101);
        }
    }

    // 将进行剪裁后的图片显示到UI界面上
    private void setPicToView(Intent picdata) {
        Bundle bundle = picdata.getExtras();
        if (bundle != null) {
            Bitmap photo = bundle.getParcelable("data");
//            转变成圆形图片
            bitmap = CircleUtil.toRoundBitmap(getActivity(), photo);
            fragmentZiliaoImg.setImageBitmap(bitmap);
            PopupWindowUtil.cancel(SpKey.IMG, null);
        }
    }

    /**
     * 发送广播修改头像
     */
    private void sendImageBroadcast(Bitmap bitmap, boolean isInfo) {
        Intent intent = new Intent();
        intent.setAction("image");
        intent.putExtra("image", bitmap);
        intent.putExtra("nc", nc);
        intent.putExtra("sex", sex1);
        intent.putExtra("sr", sr);
        intent.putExtra("dq", dq);
        intent.putExtra("is_business", is_business);
        intent.putExtra("isInfo", isInfo);
        getActivity().sendBroadcast(intent);
    }

    /**
     * 使用系统当前日期加以调整作为照片的名称
     *
     * @return
     */
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }
}
